#!/bin/bash

echo "=================================================="
echo "           MinFS EasyClient 测试启动脚本"
echo "=================================================="
echo

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查Java环境
echo "检查Java环境..."
if ! command -v java &> /dev/null; then
    echo -e "${RED}错误: 未找到Java环境，请安装Java 8+${NC}"
    exit 1
fi

# 检查Maven环境
echo "检查Maven环境..."
if ! command -v mvn &> /dev/null; then
    echo -e "${RED}错误: 未找到Maven环境，请安装Maven 3.6+${NC}"
    exit 1
fi

echo -e "${GREEN}环境检查通过...${NC}"
echo

# 检查服务依赖
echo "检查服务依赖状态..."
echo

# 检查ZooKeeper
echo "检查 ZooKeeper (localhost:2181)..."
if netstat -an 2>/dev/null | grep -q ":2181.*LISTEN" || ss -an 2>/dev/null | grep -q ":2181.*LISTEN"; then
    echo -e "${GREEN}✓ ZooKeeper 服务运行中${NC}"
else
    echo -e "${YELLOW}✗ ZooKeeper 服务未运行${NC}"
    echo "  请先启动 ZooKeeper 服务"
fi

# 检查MetaServer
echo "检查 MetaServer (localhost:8300)..."
if netstat -an 2>/dev/null | grep -q ":8300.*LISTEN" || ss -an 2>/dev/null | grep -q ":8300.*LISTEN"; then
    echo -e "${GREEN}✓ MetaServer 服务运行中${NC}"
else
    echo -e "${YELLOW}✗ MetaServer 服务未运行${NC}"
    echo "  请先启动 MetaServer 服务"
fi

# 检查DataServer
echo "检查 DataServer (localhost:8400+)..."
if netstat -an 2>/dev/null | grep -q ":8400.*LISTEN" || ss -an 2>/dev/null | grep -q ":8400.*LISTEN"; then
    echo -e "${GREEN}✓ DataServer 服务运行中${NC}"
else
    echo -e "${YELLOW}○ DataServer 状态未知（端口号可能不同）${NC}"
fi

echo
echo "按 Enter 继续运行测试，或 Ctrl+C 取消..."
read -r

echo
echo "--------------------------------------------------"
echo "编译客户端代码..."
echo "--------------------------------------------------"

# 编译项目
if mvn clean compile -q; then
    echo -e "${GREEN}编译成功!${NC}"
else
    echo -e "${RED}编译失败，请检查代码${NC}"
    exit 1
fi

echo
echo "--------------------------------------------------"
echo "运行客户端测试..."
echo "--------------------------------------------------"
echo

# 运行测试
mvn exec:java -Dexec.mainClass="com.ksyun.campus.client.ClientTest" -q

# 检查运行结果
if [ $? -eq 0 ]; then
    echo
    echo "--------------------------------------------------"
    echo -e "${GREEN}✓ 客户端测试运行完成${NC}"
    echo "--------------------------------------------------"
else
    echo
    echo "--------------------------------------------------"
    echo -e "${RED}✗ 客户端测试运行失败${NC}"
    echo "请查看错误信息并检查服务状态"
    echo "--------------------------------------------------"
fi

echo
echo "测试完成！"
